package com.boot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.dto.PageDTO;
import com.boot.entity.Result;
import com.boot.entity.SysUser;
import com.boot.service.ISysUserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/sys-user")
public class SysUserController {

    @Resource
    private ISysUserService userService;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @GetMapping("/page")
    public Result<Page<SysUser>> page(PageDTO pageDTO) {
        Page<SysUser> page = new Page<>(pageDTO.getPage(), pageDTO.getSize());
        Page<SysUser> userPage = userService.page(page);
        List<SysUser> records = userPage.getRecords();
        for (SysUser record : records) {
            record.setPassword(null);
        }
        return Result.success(userPage);
    }

    @GetMapping
    public Result<List<SysUser>> list() {
        List<SysUser> userList = userService.list();
        for (SysUser sysUser : userList) {
            sysUser.setPassword(null);
        }
        return Result.success(userList);
    }

    @GetMapping("/{id}")
    public Result<SysUser> getById(@PathVariable Long id) {
        SysUser user = userService.getById(id);
        if (user == null) return Result.fail("用户不存在");
        user.setPassword(null); // 不返回密码
        return Result.success(user);
    }

    @PostMapping
    public Result<String> add(@Valid @RequestBody SysUser user) {
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            return Result.fail("用户名不能为空");
        }
        if (user.getPassword() == null || user.getPassword().length() < 6) {
            return Result.fail("密码不能少于6位");
        }

        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setEnabled((byte) 1);
        if (userService.save(user)) {
            return Result.success("添加成功");
        }
        return Result.fail("添加失败");
    }

    @PutMapping
    public Result<String> update(@RequestBody SysUser user) {
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            userService.updateById(user);
        } else {
            user.setPassword(null);
            userService.updateWithoutPassword(user);
        }
        return Result.success("更新成功");
    }

    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        if (userService.removeById(id)) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }
}
